﻿//-----------------------------------------------------------------------
// <copyright file="WeakAction.cs" company="WpfDevelopment.com">
//     Copyright WpfDevelopment.com. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace WpfDevelopment.MVVM
{
    using System;
    using System.Diagnostics;
    using System.Reflection;
    using System.Diagnostics.Contracts;

    /// <summary>
    /// An action as weak reference
    /// </summary>
    internal class WeakAction : WeakReference
    {
        /// <summary>
        /// The method to have a weak reference to
        /// </summary>
        private readonly MethodInfo method;

        /// <summary>
        /// Initializes a new instance of the <see cref="WeakAction"/> class.
        /// </summary>
        /// <param name="action">The action.</param>
        internal WeakAction(Action<object> action)
            : base(action.Target)
        {
            Contract.Requires<ArgumentNullException>(action != null);
            this.method = action.Method;
        }

        /// <summary>
        /// Creates the action.
        /// </summary>
        /// <returns>the action inside this weak reference</returns>
        internal Action<object> CreateAction()
        {
            if (!this.IsAlive)
            {
                return null;
            }

            if (this.Target == null)
            {
                Debug.WriteLine("action.Target is null");
                return null;
            }

            return Delegate.CreateDelegate(typeof(Action<object>), this.Target, this.method.Name) as Action<object>;
        }
    }
}
